package com.google.ant.extensions.utils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import org.apache.tools.ant.util.JAXPUtils;

public final class XMLUtils {

    private XMLUtils() {
    }

    public static DocumentBuilder getParser() throws ParserConfigurationException {
        return JAXPUtils.getDocumentBuilder();
    }

    public static Document parse(InputSource is) throws ParserConfigurationException, SAXException,
        IOException {
        return getParser().parse(is.getSystemId());
    }

    public static Document parse(File is) throws ParserConfigurationException, SAXException,
        IOException {
        return getParser().parse(is);
    }

    public static Document parse(InputStream in) throws ParserConfigurationException, SAXException,
        IOException {
        return getParser().parse(in);
    }

    public static Document parse(String in) throws ParserConfigurationException, SAXException, IOException {
        return parse(in.getBytes());
    }

    public static Document parse(byte[] in) throws ParserConfigurationException, SAXException, IOException {
        return getParser().parse(new ByteArrayInputStream(in));
    }

    public static List<String> getStringList(NodeList nodelist) {
        List<String> results = new ArrayList<String>();
        for (int i = 0; i < nodelist.getLength(); i++) {
            Node node = nodelist.item(i);
            results.add(node.getNodeValue());
        }
        return results;
    }
}
